/**
 * BaseDTO - 数据传输对象基类
 * 提供数据验证、转换和格式化的通用功能
 */
class BaseDTO {
    constructor(data = {}) {
        this.data = data;
        this.errors = [];
        this.validationRules = {};
        this.transformRules = {};
    }

    /**
     * 设置验证规则
     * @param {Object} rules - 验证规则对象
     */
    setValidationRules(rules) {
        this.validationRules = rules;
        return this;
    }

    /**
     * 设置转换规则
     * @param {Object} rules - 转换规则对象
     */
    setTransformRules(rules) {
        this.transformRules = rules;
        return this;
    }

    /**
     * 验证数据
     * @returns {boolean} - 验证是否通过
     */
    validate() {
        this.errors = [];
        
        for (const [field, rules] of Object.entries(this.validationRules)) {
            const value = this.data[field];
            
            // 必填验证
            if (rules.required && (value === undefined || value === null || value === '')) {
                this.addError(field, `${field} is required`);
                continue;
            }
            
            // 如果字段为空且非必填，跳过其他验证
            if (value === undefined || value === null || value === '') {
                continue;
            }
            
            // 类型验证
            if (rules.type && !this.validateType(value, rules.type)) {
                this.addError(field, `${field} must be of type ${rules.type}`);
            }
            
            // 长度验证
            if (rules.minLength && value.length < rules.minLength) {
                this.addError(field, `${field} must be at least ${rules.minLength} characters`);
            }
            
            if (rules.maxLength && value.length > rules.maxLength) {
                this.addError(field, `${field} must not exceed ${rules.maxLength} characters`);
            }
            
            // 数值范围验证
            if (rules.min !== undefined && Number(value) < rules.min) {
                this.addError(field, `${field} must be at least ${rules.min}`);
            }
            
            if (rules.max !== undefined && Number(value) > rules.max) {
                this.addError(field, `${field} must not exceed ${rules.max}`);
            }
            
            // 正则表达式验证
            if (rules.pattern && !rules.pattern.test(value)) {
                this.addError(field, `${field} format is invalid`);
            }
            
            // 枚举值验证
            if (rules.enum && !rules.enum.includes(value)) {
                this.addError(field, `${field} must be one of: ${rules.enum.join(', ')}`);
            }
            
            // 自定义验证函数
            if (rules.custom && typeof rules.custom === 'function') {
                const customResult = rules.custom(value, this.data);
                if (customResult !== true) {
                    this.addError(field, customResult || `${field} validation failed`);
                }
            }
        }
        
        return this.errors.length === 0;
    }

    /**
     * 类型验证
     * @param {*} value - 要验证的值
     * @param {string} type - 期望的类型
     * @returns {boolean}
     */
    validateType(value, type) {
        switch (type) {
            case 'string':
                return typeof value === 'string';
            case 'number':
                return typeof value === 'number' && !isNaN(value);
            case 'integer':
                return Number.isInteger(Number(value));
            case 'boolean':
                return typeof value === 'boolean';
            case 'email':
                return typeof value === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
            case 'url':
                try {
                    new URL(value);
                    return true;
                } catch {
                    return false;
                }
            case 'date':
                return !isNaN(Date.parse(value));
            case 'array':
                return Array.isArray(value);
            case 'object':
                return typeof value === 'object' && value !== null && !Array.isArray(value);
            default:
                return true;
        }
    }

    /**
     * 添加验证错误
     * @param {string} field - 字段名
     * @param {string} message - 错误信息
     */
    addError(field, message) {
        this.errors.push({ field, message });
    }

    /**
     * 获取验证错误
     * @returns {Array} - 错误数组
     */
    getErrors() {
        return this.errors;
    }

    /**
     * 检查是否有错误
     * @returns {boolean}
     */
    hasErrors() {
        return this.errors.length > 0;
    }

    /**
     * 转换数据
     * @returns {Object} - 转换后的数据
     */
    transform() {
        const transformed = { ...this.data };
        
        for (const [field, transformer] of Object.entries(this.transformRules)) {
            if (transformed[field] !== undefined && transformed[field] !== null) {
                if (typeof transformer === 'function') {
                    transformed[field] = transformer(transformed[field]);
                } else if (transformer === 'trim') {
                    transformed[field] = String(transformed[field]).trim();
                } else if (transformer === 'lowercase') {
                    transformed[field] = String(transformed[field]).toLowerCase();
                } else if (transformer === 'uppercase') {
                    transformed[field] = String(transformed[field]).toUpperCase();
                } else if (transformer === 'number') {
                    transformed[field] = Number(transformed[field]);
                } else if (transformer === 'boolean') {
                    transformed[field] = Boolean(transformed[field]);
                }
            }
        }
        
        return transformed;
    }

    /**
     * 获取清理后的数据（仅包含定义的字段）
     * @returns {Object} - 清理后的数据
     */
    getCleanData() {
        const cleanData = {};
        const allowedFields = Object.keys(this.validationRules);
        
        for (const field of allowedFields) {
            if (this.data[field] !== undefined) {
                cleanData[field] = this.data[field];
            }
        }
        
        return cleanData;
    }

    /**
     * 验证并转换数据
     * @returns {Object} - 包含验证结果和转换数据的对象
     */
    validateAndTransform() {
        const isValid = this.validate();
        
        if (!isValid) {
            return {
                isValid: false,
                errors: this.getErrors(),
                data: null
            };
        }
        
        const transformedData = this.transform();
        
        return {
            isValid: true,
            errors: [],
            data: transformedData
        };
    }

    /**
     * 静态方法：创建DTO实例并验证
     * @param {Object} data - 要验证的数据
     * @param {Object} rules - 验证规则
     * @param {Object} transformRules - 转换规则
     * @returns {Object} - 验证结果
     */
    static validateData(data, rules, transformRules = {}) {
        const dto = new this(data);
        dto.setValidationRules(rules);
        dto.setTransformRules(transformRules);
        return dto.validateAndTransform();
    }
}
export default BaseDTO;
